package com.example.reward.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.reward.R;
import com.example.reward.fragments.HistoryDetailActivity;
import com.example.reward.response.RewardResultDto;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> {

    private List<RewardResultDto> historyList;
    private Context context;

    public HistoryAdapter(Context context, List<RewardResultDto> historyList) {
        this.context = context;
        this.historyList = historyList;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView titleText;
        public TextView timeText;

        public ViewHolder(View itemView) {
            super(itemView);
            titleText = itemView.findViewById(R.id.historyTitleText);
            timeText = itemView.findViewById(R.id.historyTimeText);
        }
    }

    @NonNull
    @Override
    public HistoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_history, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull HistoryAdapter.ViewHolder holder, int position) {
        final RewardResultDto item = historyList.get(position);
        String timestamp = formatTimestamp(item.getTimestamp());
        String title = "总奖励：" + item.getTotalReward();
        holder.titleText.setText(title);
        holder.timeText.setText(timestamp);

        holder.itemView.setOnClickListener(v -> {
            Intent intent = new Intent(context, HistoryDetailActivity.class);
            intent.putExtra("rewardItem", item);
            context.startActivity(intent);
        });
    }

    private String formatTimestamp(long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        return sdf.format(date);
    }


    @Override
    public int getItemCount() {
        return historyList.size();
    }
}

